
var app = getApp();
var util = require('../../utils/util.js');
var Bmob = require('../../utils/bmob.js');
var common = require('../../utils/common.js')
Page({
  data: {
    goodsList: [],//商品列表
    selectAddress: {},//选中的地址
    discountList: [],//打折列表
    discountListText: [],
    selectDiscountInfo:'',//选中的打折的信息
    selectDiscountIndex: 0,//选中的打折信息的下标
    orderRemark: '',//买家留言
    is_self_delivery: 0,
    has_seckill: 1,
    express_fee: '',//邮费
    balance: '',//余额
    useBalance: true,//是否使用余额
    deduction: '',
    discount_cut_price: '',
    original_price: '',
    totalPayment: '',
    shopAddress: '',
    noAdditionalInfo: true,
    is_group: '',
    exchangeCouponData: {
      dialogHidden: true,
      goodsInfo: {},
      selectModelInfo: {},
      hasSelectGoods: false,
      voucher_coupon_goods_info: {}
    }
    , 
    
  },
  isFromSelectAddress: false,
  franchisee_id: '',
  cart_id_arr: [],
  cart_data_arr: [],
  requesting: false,
  additional_info: {},
  is_group: '',
  inputTimer: '',
  onLoad: function (options) {
    this.franchisee_id = options.franchisee || '';
  
    this.cart_id_arr = options.cart_arr ? decodeURIComponent(options.cart_arr).split(',') : [];
    
    this.dataInitial();
   // this.getAddressInfo();
   
   // this.is_group = options.is_group;
   // this.setData({ is_group: options.is_group });
  },
  dataInitial: function () {
     
     this.getCartList();
       //  this.getCalculationInfo();
   // this.getShopAddress();

  },
  onShow: function () {
    if (this.isFromSelectAddress) {
      this.getCalculationInfo();
      this.isFromSelectAddress = false;
    }
  },
 
  getCartList: function () {
    var that = this;
     
    var goodsList = [];
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;     //当前用户的objectId
    shoppingCart.equalTo("users", isme);
    shoppingCart.include("goodsInfo");
    shoppingCart.find({
      success: function (res) {
        var data = [];

        if (that.cart_id_arr.length) {
          for (var i = 0; i <= res.length - 1; i++) {
            if (that.cart_id_arr.indexOf(res[i].id) >= 0) {
              data.push(res[i]);
            }

          }
        } else {
          data = res;
        }
      
        for (var i = 0; i <= data.length - 1; i++) {
          var goods = data[i].attributes;
          goods.id = data[i].id;
          if (goods.is_seckill == 1) {

            that.data.has_seckill = 1;

          }
          that.cart_data_arr.push({
            cart_id: goods.shopping_car_id,
            goods_id: goods.goods_id,
            model_id: goods.model_id,
            num: goods.num
          });
          goodsList.push(goods);
        }
        that.franchisee_id=goodsList[0].goodsInfo.FranchiseeId.objectId;

        that.getShopAddress(that.franchisee_id);
        that.setData({
          goodsList: goodsList
        });
        that.getbenefits(goodsList);
      }
    })
  },

  getAddressList: function () {
    var _this = this;
    app.chooseAddress({
      success: function (res) {
        console.log(res);
        _this.setData({
          selectAddress: res,
        })
      }
    })


  },
  getAddressInfo: function () {
    var AddressList = Bmob.Object.extend("Myaddress");
    var that = this;
    var addressList = new Bmob.Query(AddressList);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;   //当前用户的objectId
    addressList.equalTo("users", isme);
    addressList.find({
      success: function (res) {
     
        for (var i = 0; i < res.length; i++) {

          if (res[i].attributes.default) {
            var addressInfo = {};
            addressInfo = res[i].attributes;
            addressInfo.id = res[i].id;

            that.setData({
              selectAddress: addressInfo,

            })
          }

        }

      },
      error: function (e) {
        console.log(e);
      }


    })

    console.log(this.data.selectAddress);
  },


  is_in: function (startTime, endTime) {
   
    var server_time = util.formatTime();
    let systemInfo = wx.getSystemInfoSync().system;
    let isiphone = systemInfo.indexOf('iOS') != -1;

    if (isiphone && /\-/g.test(endTime)) {
      endTime = endTime.replace(/\-/g, '/');
    }
    if (isiphone && /\-/g.test(startTime)) {
      startTime = startTime.replace(/\-/g, '/');
    }
    if (isiphone && /\-/g.test(server_time)) {
      server_time = server_time.replace(/\-/g, '/');
    }
    if (/^\d+$/.test(endTime)) {
      endTime = endTime * 1000;
    }
    if (/^\d+$/.test(startTime)) {
      startTime = startTime * 1000;
    }
    if (/^\d+$/.test(server_time)) {
      server_time = server_time * 1000;
    }
    var server_time = util.formatTime();
    let end_date = new Date(endTime),
      start_date = new Date(startTime),
      server_date = new Date(server_time),
      interval,
      isfirst = true,
      difference1 = server_date - start_date,
       difference2=end_date-server_date;
       if (difference1 > 0 && difference2>0)
           return true;
           else 
           return false;

  },


  getCalculationInfo: function (selectDiscountInfo1,selectDiscountIndex1,goodList) {
    var _this = this;
    var totalPrice = 0.0;
    var express_fee = 0.0;
    var original_price = 0.0;
    var discount_cut_price=0.0;    
    var goods = _this.data.goodsList || goodList;
    var selectDiscountInfo = selectDiscountInfo1 || _this.data.selectDiscountInfo;
    var selectDiscountIndex = selectDiscountIndex1 || _this.data.selectDiscountIndex;

    // _this.getAddressInfo();
    if (goods) {

      for (var i = 0; i < goods.length; i++) {

        original_price += goods[i].price * goods[i].num;
        //totalPrice += goods[i].price * goods[i].num;
        express_fee += (goods[i].goodsInfo.express_fee||0);
       
      }

      totalPrice = express_fee + original_price;
    }
    if (selectDiscountIndex!=0) {
      
      switch (selectDiscountInfo.type) {
        case 0:
          
          totalPrice = _this.manjian(selectDiscountInfo.value, Number(selectDiscountInfo.condition), original_price);
          discount_cut_price = original_price-totalPrice ;
         break;
        case 1:
          
          totalPrice = _this.discount(selectDiscountInfo.value, original_price);
          discount_cut_price = original_price - totalPrice;
          break;
        case 3:
        
          totalPrice = _this.deduction(selectDiscountInfo.value, original_price);
          discount_cut_price = original_price - totalPrice;
          break;

      }
    } else {
      //selectDiscountIndex = 0;
   
     // console.log(selectDiscountInfo)
    }
    _this.setData({
      //  selectAddress: info.address,
      //  discountList: benefits,
      selectDiscountIndex: selectDiscountIndex,
      selectDiscountInfo: selectDiscountInfo,
      
      express_fee: express_fee,
      discount_cut_price: discount_cut_price.toFixed(2),
      //balance: info.balance,
      // deduction: info.use_balance,
      original_price: original_price,
      totalPayment: totalPrice,

      //noAdditionalInfo: additional_info_goods.length ? false : true
    })
    // app.setPreviewGoodsInfo(additional_info_goods);


  },
  getbenefits:function(goods){
    var that=this;
    var DiscountInfo = { discountList:[],
      discountListText:[]};
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;

    var CouponList = Bmob.Object.extend("mycoupon");
    var couponList = new Bmob.Query(CouponList);
    couponList.equalTo("userInfo", isme);
    couponList.include("couponInfo"); 
     couponList.find({
      success: function (res) {
        //var goods=res;
        console.log(res);
        var discountList=[];
        var discountListText=[];
        
    if(res.length)
for(var i=0;i<res.length;i++)
{
  var start_time = res[i].get("couponInfo").start_use_date;
  var end_time = res[i].get("couponInfo").end_use_date;
  var status = res[i].get("status");
  var enable_status = res[i].get("couponInfo").enable_status;
  
  if (that.is_in(start_time, end_time) && status == 1 && enable_status==1)
        { discountList.push(res[i].get("couponInfo"));

    discountListText.push(res[i].get("couponInfo").title);
        }

}
    discountList.unshift({});
    discountListText.unshift('不使用优惠');
    that.setData({
      discountList: discountList,
      discountListText: discountListText

    })
    that.getCalculationInfo(discountList[0],0,goods);
        },
      complete: function () {

      }
    });


  },

  //优惠卷满减
  manjian: function (value, value1,totalPayment){
    
  if (totalPayment>value1)
  totalPayment = totalPayment-value;
    return totalPayment;
  },
//优惠卷打折
  discount: function (value, totalPayment){
   
    totalPayment = totalPayment*(1-value/100);
    return totalPayment
  },
  //优惠劵抵扣
  deduction: function (value, totalPayment){
    if (totalPayment > value)
    totalPayment = totalPayment-value;
    
    return totalPayment


  },

  
  getShopAddress: function (franchiseeid) {
    var that = this;
    var FranchiseeInfo = Bmob.Object.extend("Franchisee");
    var franchisee = new Bmob.Query(FranchiseeInfo);
   franchisee.get(franchiseeid,{
     success: function (res) {
       // The object was retrieved successfully.
       that.setData({
         shopAddress: res
       });
       
     },
     error: function (result, error) {
       console.log("查询失败");
     }


   })

  },
  remarkInput: function (e) {
    var value = e.detail.value;
    if (value.length > 30) {
      app.showModal({
        content: '最多只能输入30个字'
      });
      value = value.slice(0, 30);
    }

    this.setData({
      orderRemark: value
    });
  },
  previewImage: function (e) {
    app.previewImage({
      current: e.currentTarget.dataset.src
    });
  },
  clickMinusButton: function (e) {

    var index = e.currentTarget.dataset.index,
      num = this.data.goodsList[index].num,
     
      fromUserCenterEle = this.data.isFromUserCenterEle,
      franchiseeId = this.franchiseeId,
      deleteId = this.data.goodsList[index].id,
      that = this;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
  
    if (num - 1 <= 0) {
      app.showModal({
        content: '确定从购物车删除该商品？',
        showCancel: true,
        confirm: function () {

          shoppingCart.get(deleteId, {
            success: function (object) {
              // The object was retrieved successfully.
              object.destroy({
                success: function (deleteObject) {
                  console.log('删除日记成功');
                  //deleteIdArr.push(+list[i].id);
                  that.setData({
                    selectAll: false
                  });
                  that.getShoppingCartData();
                },
                error: function (object, error) {
                  console.log('删除日记失败');
                }
              });
            },
            error: function (object, error) {
              console.log("query object fail");
            }
          });


        }
      })
      return;
    }
    this.changeGoodsNum(index, 'minus');

  },
  clickPlusButton: function (e) {
    var index = e.currentTarget.dataset.index;
    this.changeGoodsNum(index, 'plus');
  },
  changeGoodsNum: function (index, type) {
    var that = this;
    var goods = that.data.goodsList[index],
      goodsId = goods.id,
      currentNum = +goods.num,

      targetNum = type == 'plus' ? currentNum + 1 : currentNum - 1,
      data = {};

    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    var subNameIndex = goods.subNameIndex;
    var modelNameIndex = goods.modelNameIndex;
    var stock;

    if (goods.is_seckill)
      stock = goods.goodsInfo.models[subNameIndex].models[modelNameIndex].seckill_stock;
    else
    { stock = goods.goodsInfo.models[subNameIndex].models[modelNameIndex].stock; }


    if (targetNum > stock) {
      app.showModal({
        content: '库存不足'
      });
      return;
    }


    shoppingCart.get(goodsId, {
      success: function (result) {
        // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
        result.set('num', targetNum);
        result.save({

          success: function () {
         
            data = {};
            data['goodsList[' + index + '].num'] = targetNum;
          
            that.setData(data);
            that.getCalculationInfo();
          },

        });

      },
      error: function (object, error) {
        console.log("query object fail");
        data = {};
        that.cart_data_arr[index].num = currentNum;
        data['goodsList[' + index + '].num'] = currentNum;
        that.setData(data);
      }
    });

  },
  deleteGoods: function () {
   
    var list = this.data.goodsList,
      franchiseeId = this.franchiseeId,
      fromUserCenterEle = this.data.isFromUserCenterEle,
      that = this;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    for (var i = list.length - 1; i >= 0; i--) {


      shoppingCart.get(list[i].id, {
        success: function (object) {
          // The object was retrieved successfully.
          object.destroy({
            success: function (deleteObject) {
              console.log('删除日记成功');
              //deleteIdArr.push(+list[i].id);

            },
            error: function (object, error) {
              console.log('删除日记失败');
            }
          });
        },
        error: function (object, error) {
          console.log("query object fail");
        }
      });


    }


  },

  confirmPayment1: function (e) {
    var list = this.data.goodsList,
      that = this,
      selected_benefit = this.data.selectDiscountInfo,
      hasWritedAdditionalInfo = false;



    if (this.data.is_self_delivery == 0 && !this.data.selectAddress.id) {
      app.showModal({
        content: '请选择地址'
      });
      return;
    }

    for (var key in this.additional_info) {
      if (key !== undefined) {
        hasWritedAdditionalInfo = true;
        break;
      }
    }
    if (!this.data.noAdditionalInfo && !hasWritedAdditionalInfo) {
      app.showModal({
        content: '请填写商品补充信息'
      });
      return;
    }

    if (this.requesting) {
      return;
    }
    this.requesting = true;

    app.sendRequest({
      url: '/index.php?r=AppShop/addCartOrder',
      method: 'post',
      data: {
        cart_arr: this.cart_data_arr,
        formId: e.detail.formId,
        sub_shop_app_id: this.franchisee_id,
        selected_benefit: selected_benefit,
        is_balance: this.data.useBalance ? 1 : 0,
        is_self_delivery: this.data.is_self_delivery,
        remark: this.data.orderRemark,
        address_id: this.data.selectAddress.id,
        additional_info: this.additional_info,
        voucher_coupon_goods_info: this.data.exchangeCouponData.voucher_coupon_goods_info
      },
      success: function (res) {
        that.payOrder(res.data);
      },
      fail: function () {
        that.requesting = false;
      },
      successStatusAbnormal: function () {
        that.requesting = false;
      }
    });
  },


  confirmPayment: function (e) {
    var list = this.data.goodsList,
      that = this,
      selected_benefit = that.data.selectDiscountInfo,
      hasWritedAdditionalInfo = false;
   
    //  order.set("has_seckill", that.data.has_seckill);
    if (this.data.is_self_delivery == 0 && !this.data.selectAddress.userName) {
      app.showModal({
        content: '请选择地址'
      });
      return;
    }

    for (var key in this.additional_info) {
      if (key !== undefined) {
        hasWritedAdditionalInfo = true;
        break;
      }
    }
    if (!this.data.noAdditionalInfo && !hasWritedAdditionalInfo) {
      app.showModal({
        content: '请填写商品补充信息'
      });
      return;
    }

    if (this.requesting) {
      return;
    }
    this.requesting = true;
    console.log("confirm")
    that.modifyGoods();
  

  },
  modifyGoods: function (id) {
    var list = this.data.goodsList,

      franchiseeId = this.franchiseeId,
      fromUserCenterEle = this.data.isFromUserCenterEle,
      is_complete=false,
      that = this;
   
   // var Goods = Bmob.Object.extend("goods");
   // var goods = new Bmob.Query(Goods);
    var j=0;
    for (var i = 0; i < list.length;i++) {
      var good_Info = list[i];
      var Goods = Bmob.Object.extend("goods");
      var goods = new Bmob.Query(Goods);
   // console.log("i=",i);
  //  console.log("j=", j);
      var num = good_Info.num;
      console.log(good_Info)
      goods.get(good_Info.goods_id).then(function(res){
        console.log("i=", i);
       // console.log("j=", j);
        var subNameIndex = list[j].subNameIndex;
        var modelNameIndex = list[j].modelNameIndex;
          var model_seckillstock = 0;
          var model_stock=0;
         
         // var seckill_stock = res.attributes.seckill_stock || 0;
         // var stock = res.attributes.stock - num;
         // console.log(stock)
          // The object was retrieved successfully.
          if (res.attributes.models) {
          
            var model_seckillstock = res.attributes.models[subNameIndex].models[modelNameIndex].seckill_stock || 0;
            var model_stock = res.attributes.models[subNameIndex].models[modelNameIndex].stock || 0;
            res.attributes.models[subNameIndex].models[modelNameIndex].stock -= num;
            
            if (res.attributes.is_seckill == "1") {
          
            
              var model_seckillstock = model_seckillstock - num;
              res.attributes.models[subNameIndex].models[modelNameIndex].seckill_stock = model_seckillstock;
              }
          
          }else{
            
            if (res.attributes.is_seckill == "1") {
               seckill_stock -= num;
            }
          
          }
      
          if (model_seckillstock >= 0 && model_stock>= 0) {
            res.set('sales', res.attributes.sales + num);
            res.set('models', res.attributes.models);
            
             //console.log("subName",list[j].subNameIndex);
            // console.log("modelName",list[j].modelNameIndex);
             j++;
             res.save();
           
            
          }
          else {
         
            wx.showToast({
              title: '库存不足',
              icon: 'success',
              duration: 2000,
              
            })
           return;
          }
        },
        function (object, error) {
          console.log("query object fail");
          return;
        })
   

    }
    console.log("modify")

   that.order();

  },
  order:function(){
    var list = this.data.goodsList,
      that=this,
      selected_benefit = that.data.selectDiscountInfo,
      hasWritedAdditionalInfo = false;
    var currentUser = Bmob.User.current();
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Franchisee();
    franchisee.id = that.franchisee_id||'';
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;
    var  address= that.data.selectAddress;
    var Order = Bmob.Object.extend("orderList");
    var order = new Order();
    order.set("sub_shop_info", franchisee);
    order.set("current_goods_type", Number(that.data.goodsList[0].goodsInfo.goods_type));
    order.set("goods_info", that.data.goodsList||[]);
    order.set("users", isme);
    order.set("original_price", that.data.original_price);
    order.set("order_total_price", that.data.totalPayment);
    order.set("express_fee", that.data.express_fee);
    order.set("status", 0);
    order.set("remark", that.data.orderRemark);
    order.set("discount_cut_price", that.data.discount_cut_price);
    order.set("address_info", address); 
    order.set("is_self_delivery", Number(that.data.is_self_delivery));
    console.log(order)
    order.save(null, {
      success: function (res) {
        that.notice(res.id);
        that.payOrder(res.id,that.data.goodsList);
        that.deleteGoods();

      },
      error: function (e) {
        that.requesting = false;
        console.log(e);
      },
  
    });
    console.log("order")

  },
  payOrder: function (order_Id,goodsList) {
    var that = this;
    var orderInfo={};
    console.log(order_Id);
    var openId = wx.getStorageSync('openid');
    function paySuccess(orderId) {
      var pagePath = '/pages/goodsOrderPaySuccess/goodsOrderPaySuccess?detail=' + order_Id + (that.franchisee_id ? '&franchisee=' + that.franchisee_id : '');
      if (orderId) {
        var Order = Bmob.Object.extend("orderList");
        var order = new Bmob.Query(Order);

        order.get(order_Id, {
          success: function (result) {
            // 回调中可以取得这个 GameScore 对象的一个实例，然后就可以修改它了
            //orderInfo=result.attributes;
          
            result.set('status', 1);
            
            result.save();

            // The object was retrieved successfully.
          },
          error: function (object, error) {

          }
        });
      }
      app.turnToPage(pagePath, 1);

    }

    function payFail() {
      if (that.is_group) {
        app.turnToPage('/pages/groupOrderDetail/groupOrderDetail?id=' + order_Id, 1);
      } else {
        app.turnToPage('/pages/goodsOrderDetail/goodsOrderDetail?detail=' + order_Id, 1);
      }
    }

    Bmob.Pay.wechatPay(that.data.totalPayment, goodsList[0].title+'...', '邻舍边', openId).then(function (resp) {
     
      that.setData({
        loading: true,
        dataInfo: resp
      })
      //服务端返回成功
      var timeStamp = resp.timestamp,
        nonceStr = resp.noncestr,
        packages = resp.package,
        orderId = resp.out_trade_no,//订单号，如需保存请建表保存。
        sign = resp.sign;
      //打印订单号
      console.log(orderId, orderId);

      //发起支付
      wx.requestPayment({
        'timeStamp': timeStamp,
        'nonceStr': nonceStr,
        'package': packages,
        'signType': 'MD5',
        'paySign': sign,
        'success': function (res) {
          //付款成功,这里可以写你的业务代码
          console.log(res);
          that.paynotice(packages,order_Id);
          paySuccess(order_Id);
        // app.wxPaySuccess(param);

        },
        'fail': function (res) {
          //付款失败
          console.log('付款失败');
          console.log(res);
          paySuccess(order_Id);
          payFail();
          if (res.errMsg === 'requestPayment:fail cancel') {
           // param.fail();
            return;
          }
          app.showModal({
            content: '支付失败',
            complete: param.fail
          })
          app.wxPayFail(param, res.errMsg);
        }
      })

    }, function (err) {
      payFail();
      console.log('服务端返回失败');
      common.showTip(err.message, 'loading', {}, 6000);
      console.log(err);
    });

  },

  paynotice: function (formId, order_Id){
var that=this;
var tradeDateTime = util.formatTime(new Date());
    var currentUser = Bmob.User.current();
    var temp = {
      "touser": currentUser.get("openid"),
      "template_id": "DCJzwWAspt5VydkPMt8aJH41JbiBGt3Nt_9F5kcon9g",
      "page": "",
      "form_id": formId,
      "data": {
        "keyword1": {
          "value": order_Id,
          "color": "#173177"
        },
        "keyword2": {
          "value": tradeDateTime
        },
        "keyword3": {
          "value":that.data.totalPayment
        },
        "keyword4": {
          "value": "联系客服17792364930"
        },
       
      },

    }
    Bmob.sendMessage(temp).then(function (obj) {
      console.log('发送成功')
    },
      function (err) {
        console.log(err)
      });
  },
  wxPay: function (param) {

    var that = this;
    wx.requestPayment({
      'timeStamp': param.timeStamp,
      'nonceStr': param.nonceStr,
      'package': param.package,
      'signType': 'MD5',
      'paySign': param.paySign,
      success: function (res) {
        app.wxPaySuccess(param);
        param.success();
      },
      fail: function (res) {
        if (res.errMsg === 'requestPayment:fail cancel') {
          param.fail();
          return;
        }
        app.showModal({
          content: '支付失败',
          complete: param.fail
        })
        app.wxPayFail(param, res.errMsg);
      }
    })
  },
  discountChange: function (e) {
    var index = Number(e.detail.value);
    
    this.setData({
     
      'exchangeCouponData.hasSelectGoods': false,
      'exchangeCouponData.voucher_coupon_goods_info': {}
    })
    this.getCalculationInfo(this.data.discountList[index],index);
  },
  goToMyAddress: function () {
    var addressId = this.data.selectAddress.id;
    this.isFromSelectAddress = true;
    app.turnToPage('/pages/myAddress/myAddress?id=' + addressId);
  },
  notice:function(orderId){
    var tradeDateTime = util.formatTime(new Date());
    console.log(tradeDateTime)
    var customerInfo=this.data.selectAddress||'';
    console.log(customerInfo)
    var temp = {
      "touser": "oUxY3w5OL1GacVD-dJcZF8lmAG0k",
      "template_id": "K9-6_Ayj4MLC2yvwY60-cq18tngJHAlqDfsOvv3D7a8",
      "url": "https://www.bmob.cn/",
      "data": {
        "first": {
          "value": "有客户下单快速找他",
         
        },
        "tradeDateTime": {
          "value": tradeDateTime
        },
        "orderType": {
          "value": orderId
        },
        "customerInfo": {
          "value": "姓名" + customerInfo.userName + "手机" + customerInfo.telNumber + "地址" + customerInfo.provinceName + customerInfo.cityName + customerInfo.countyName + customerInfo.detailInfo
        },

       
        "remark": {
          "value": "有人下单请及时联系"
        }
      }
    }
    console.log(temp);
    Bmob.sendMasterMessage(temp).then(function (obj) {
      console.log('发送成功');
      console.log(obj);
    }, function (err) {
      console.log(err);
    });


  },
  showAddAddress: function () {
    var _this = this;

    app.chooseAddress({
      success: function (res) {
        app.sendRequest({
          method: 'post',
          url: '/index.php?r=AppShop/AddWxAddress',
          data: {
            detailInfo: res.detailInfo || '',
            cityName: res.cityName || '',
            provinceName: res.provinceName || '',
            UserName: res.userName || '',
            telNumber: res.telNumber || '',
            district: res.district || '',
            countyName: res.countyName || ''
          },
          success: function () {
            _this.dataInitial();
          },
        })
      }
    })
  },
  makeStorePhoneCall: function () {
    app.makePhoneCall(this.data.shopAddress.shop_contact);
  },
  openStoreLocation: function () {
    var infor = this.data.shopAddress
 
           wx.openLocation({
            latitude: infor.get("latitude"),
            longitude: infor.get("longitude")
          })
         
  
  },
  useBalanceChange: function (e) {
    this.setData({
      useBalance: e.detail.value
    });
    this.getCalculationInfo();
  },
  deliveryWayChange: function (e) {
    this.setData({
      is_self_delivery: e.detail.value
    })
    this.getCalculationInfo();
  },
  goToAdditionalInfo: function () {
    app.setGoodsAdditionalInfo(this.additional_info);
    app.turnToPage('/pages/goodsAdditionalInfo/goodsAdditionalInfo');
  },
  exchangeCouponInit: function (id) {
    var _this = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/getGoods',
      data: {
        data_id: id
      },
      success: function (res) {
        var goods = res.data[0].form_data;
        var goodsModel = [];
        var selectModelInfo = {
          'models': [],
          'price': 0,
          'modelId': '',
          'models_text': '',
          'imgurl': ''
        };
        if (goods.model_items.length) {
          // 有规格
          selectModelInfo['price'] = Number(goods.model_items[0].price);
          selectModelInfo['imgurl'] = goods.model_items[0].img_url;
          selectModelInfo['modelId'] = goods.model_items[0].id;
        } else {
          selectModelInfo['price'] = Number(goods.price);
          selectModelInfo['imgurl'] = goods.cover;
        }
        for (var key in goods.model) {
          if (key) {
            goodsModel.push(goods.model[key]); // 转成数组
            selectModelInfo['models'].push(goods.model[key].subModelId[0]);
            selectModelInfo['models_text'] += '“' + goods.model[key].subModelName[0] + '” ';
          }
        }
        goods.model = goodsModel; // 将原来的结构转换成数组
        _this.setData({
          'exchangeCouponData.dialogHidden': false, // 显示模态框
          'exchangeCouponData.goodsInfo': goods,
          'exchangeCouponData.selectModelInfo': selectModelInfo
        });
      }
    });
  },
  exchangeCouponHideDialog: function () {
    this.setData({
      selectDiscountInfo: this.data.discountList[0],
      selectDiscountIndex: 0,
      'exchangeCouponData.dialogHidden': true,
      'exchangeCouponData.hasSelectGoods': false,
      'exchangeCouponData.voucher_coupon_goods_info': {}
    })
    this.getCalculationInfo();
  },
  exchangeCouponSelectSubModel: function (e) {
    var dataset = e.target.dataset,
      modelIndex = dataset.modelIndex,
      submodelIndex = dataset.submodelIndex,
      data = {},
      selectModels = this.data.exchangeCouponData.selectModelInfo.models,
      model = this.data.exchangeCouponData.goodsInfo.model,
      text = '';

    selectModels[modelIndex] = model[modelIndex].subModelId[submodelIndex];

    // 拼已选中规格文字
    for (let i = 0; i < selectModels.length; i++) {
      let selectSubModelId = model[i].subModelId;
      for (let j = 0; j < selectSubModelId.length; j++) {
        if (selectModels[i] == selectSubModelId[j]) {
          text += '“' + model[i].subModelName[j] + '” ';
        }
      }
    }
    data['exchangeCouponData.selectModelInfo.models'] = selectModels;
    data['exchangeCouponData.selectModelInfo.models_text'] = text;

    this.setData(data);
    this.exchangeCouponResetSelectCountPrice();
  },
  exchangeCouponResetSelectCountPrice: function () {
    var _this = this,
      selectModelIds = this.data.exchangeCouponData.selectModelInfo.models.join(','),
      modelItems = this.data.exchangeCouponData.goodsInfo.model_items,
      data = {};

    for (var i = modelItems.length - 1; i >= 0; i--) {
      if (modelItems[i].model == selectModelIds) {
        data['exchangeCouponData.selectModelInfo.stock'] = modelItems[i].stock;
        data['exchangeCouponData.selectModelInfo.price'] = modelItems[i].price;
        data['exchangeCouponData.selectModelInfo.modelId'] = modelItems[i].id;
        data['exchangeCouponData.selectModelInfo.imgurl'] = modelItems[i].img_url;
        break;
      }
    }
    this.setData(data);
  },
  exchangeCouponConfirmGoods: function () {
    let _this = this;
    let goodsInfo = _this.data.exchangeCouponData.goodsInfo;
    let model = goodsInfo.model;
    let selectModels = _this.data.exchangeCouponData.selectModelInfo.models;
    let model_value_str = '';
    if (selectModels.length > 0) {
      model_value_str = '(';
      for (let i = 0; i < selectModels.length; i++) {
        let selectSubModelId = model[i].subModelId;
        for (let j = 0; j < selectSubModelId.length; j++) {
          if (selectModels[i] == selectSubModelId[j]) {
            model_value_str += model[i].subModelName[j] + '|';
          }
        }
      }
      model_value_str += ')';
    }
    goodsInfo['model_value_str'] = model_value_str;
    _this.setData({
      'exchangeCouponData.dialogHidden': true,
      'exchangeCouponData.selectModelInfo': {},
      'exchangeCouponData.hasSelectGoods': true,
      'exchangeCouponData.voucher_coupon_goods_info': {
        goods_id: goodsInfo.id,
        num: 1,
        model_id: _this.data.exchangeCouponData.selectModelInfo.modelId
      },
      'exchangeCouponData.goodsInfo': goodsInfo
    });
    _this.getCalculationInfo();
  },
  inputGoodsCount: function (e) {
    let value = +e.detail.value;
    let index = e.target.dataset.index;

    if (isNaN(value) || value <= 0) {
      return;
    }
    clearTimeout(this.inputTimer);
    this.inputTimer = setTimeout(() => {
      this.changeGoodsNum(index, value);
    }, 500);
  }
})
